<?php

namespace Haozing\FastCore\Context;

use Haozing\FastCore\Context\Service\User;
use Hyperf\Context\Context;
use function Hyperf\Support\make;

class UserContext
{
    public static function get(?int $coroutineId = null): User
    {
        return Context::get(User::class, null, $coroutineId) ?? make(User::class);
    }

    public static function set(array $data, ?int $coroutineId = null): User
    {
        $authUser = make(User::class);
        $authUser->setUser($data);
        return Context::set(User::class, $authUser, $coroutineId);
    }

    public static function has(?int $coroutineId = null): bool
    {
        return Context::has(User::class, $coroutineId);
    }

    public static function getOrNull(?int $coroutineId = null): ?User
    {
        return Context::get(User::class, null, $coroutineId);
    }

    //override
    public static function override(array $data = []): void
    {
        Context::override(User::class, function (?User $authUser) use ($data) {
            //如果AuthUser为空，则创建一个
            if ($authUser == null) {
                $authUser = make(User::class);
            }
            $authUser->setUser($data);
            return $authUser;
        });
    }
}